package com.finger.forest;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionRoadModel;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 道路采集详情
 */
public class CollectionRoadDetailActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "CollectionRoadDetailAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    /**
     * 采集点的经纬度
     */
    double X,Y;

    /**
     * 位置坐标集合
     */
    List<Map<String,Object>> locList = new ArrayList<>();

    private String listStr = null;

    @Override
    protected int setView() {
        return R.layout.activity_collection_detail;
    }

    @Override
    protected void receiveData() {
        Intent intent = getIntent();
        int id = intent.getIntExtra("id",0);
        Map<String,Object> mapParams = new HashMap<>();
        mapParams.put("Id",id);
        //查询道路详情
        presenter.queryRoadDetail(mapParams);
    }

    @Override
    protected void initializeView() {
        mMapView = findViewById(R.id.mapView);
        setupMap();

        //定位当前位置
        setupLocationDisplay(false);
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = null;
            String isOnline = PrefsUtil.getString(CollectionRoadDetailActivity.this, CommonKey.ISONLINE);
            if (isOnline.equals("1")){
                map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            } else {
                String filePath = getExternalFilesDir(null).getAbsolutePath()+"/offline_map.tpk";
                Log.i(TAG,"离线文件路径："+filePath);
                TileCache tileCache = new TileCache(filePath);
                ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tileCache);
                Basemap basemap = new Basemap(tiledLayer);
                map = new ArcGISMap(basemap);
            }
            mMapView.setMap(map);
        }
    }

    @OnClick({R.id.btn_back, R.id.btn_location, R.id.btn_zoom_in , R.id.btn_zoom_out})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //定位
                case R.id.btn_location:
                    setupLocationDisplay(true);
                    break;

                //地图放大
                case R.id.btn_zoom_in:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 0.5);
                    break;

                //地图缩小
                case R.id.btn_zoom_out:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 2);
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.QUERY_ROAD_DETAIL:
                CollectionRoadModel collectionRoadModel = (CollectionRoadModel) model;
                if (collectionRoadModel != null){
                    listStr = collectionRoadModel.getLocationSet();
                    if (listStr!=null && !listStr.equals("")){
                        //显示线路
                        showPatrolTrail();
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    private void setupLocationDisplay(boolean boo) {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();

        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "定位===》"+point.toString());

                if (boo){
                    // center on tapped point
                    mMapView.setViewpointCenterAsync(point,SystemConfig.mapScale);
                }

                mLocationDisplay.removeLocationChangedListener(this);
            }
        });
    }

    LocationDisplay.LocationChangedListener locListener = new LocationDisplay.LocationChangedListener() {
        @Override
        public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
            LocationDataSource.Location location=locationChangedEvent.getLocation();
            Point point=location.getPosition();
            Log.i(TAG, "位置信息："+ point.toString());
            double locX = point.getX();
            double locY = point.getY();
            if (X==locX && Y==locY){
                Log.i(TAG, "位置未变==》不采集");
            } else {
                Log.i(TAG, "位置变动==》采集位置");
                //位置保存到集合
                Map<String,Object> locMap = new HashMap<>();
                locMap.put("longtitude", locX);
                locMap.put("latitude", locY);
                locList.add(locMap);

                X = locX;
                Y = locY;
                //先清除
                //mMapView.getGraphicsOverlays().clear();
            }
        }
    };

    /**
     * 显示巡护轨迹
     */
    private void showPatrolTrail() {
        GraphicsOverlay overlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().clear();
        mMapView.getGraphicsOverlays().add(overlay);
        //添加巡护线路
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorGreen), 2);
        Polyline polyline = createPolyline();
        overlay.getGraphics().add(new Graphic(polyline, lineSymbol));
        //定位线路
        mMapView.setViewpointGeometryAsync(polyline, 100);
    }

    private Polyline createPolyline() {
        String[] listArr = listStr.split(";");
        //创建点集合
        PointCollection borderCAtoNV = new PointCollection(SpatialReferences.getWgs84());
        for (String str : listArr) {
            String[] loc = str.split(",");
            double longtitude = Double.parseDouble(loc[0]);
            double latitude = Double.parseDouble(loc[1]);
            borderCAtoNV.add(longtitude, latitude);
        }
        //创建线
        Polyline polyline = new Polyline(borderCAtoNV);
        return polyline;
    }

}
